package com.lc.config;

import com.lc.domain.Templates;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class TemplatesUtils {


    public static void main(String[] args) throws IOException, TemplateException {
//        Configuration configuration = new Configuration(Configuration.VERSION_2_3_32);//2.3.32
        String path = System.getProperty("user.dir");

        //模板在哪里
        String inputFile = path + File.separator +"lc-code-basic"+ File.separator + "src/main/resources/templates/templates.html.ftl";
        String outputFile = path + File.separator + "template.java";
        Templates templates = new Templates();
        templates.setAuthor("lc");
        templates.setOutput("结果");
        templates.setLoop(false);
        generateAndInject(inputFile,outputFile,templates);

    }

    public static void generateAndInject(String input,String output,Object model) throws IOException, TemplateException {
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_32);//2.3.32
        //模板在哪里
//        String inputFile = path + File.separator + "src/main/resources/templates";
        File parentFile = new File(input).getParentFile();
        System.out.println(input);
        configuration.setDirectoryForTemplateLoading(parentFile);

        //字符集
        configuration.setDefaultEncoding("utf-8");

        //哪个模板
        String templateName = new File(input).getName();
        Template template = configuration.getTemplate(templateName);

        Writer writer = new FileWriter(output);
        template.process(model,writer);

        //关闭流
        writer.close();
    }
}
